package com.captjack.netty.performancetest;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.text.SimpleDateFormat;

/**
 * Description description.....
 *
 * @author Jack Sparrow
 * @version 1.0.0
 * @date 14/08/2018 13:56
 * package com.captjack.netty.performancetest
 */
public class PerformanceInvokeHandler implements InvocationHandler {

    /**
     *
     */
    private final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");

    /**
     * 需要代理的对象
     */
    private Object proxy;

    /**
     * 动态生成方法被处理过后的对象
     *
     * @param proxy 元对象
     * @return 代理后的对象
     */
    Object proxy(Object proxy) {
        this.proxy = proxy;
        return Proxy.newProxyInstance(this.proxy.getClass().getClassLoader(), this.proxy.getClass().getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result;
        long start = System.currentTimeMillis();
        System.out.println(simpleDateFormat.format(start) + " start execute！" + this.proxy.getClass().getName());
        result = method.invoke(this.proxy, args);
        long end = System.currentTimeMillis();
        System.out.println(simpleDateFormat.format(end) + " end   execute! " + this.proxy.getClass().getName());
        System.out.println("total cost: " + (end - start) + " ms.");
        return result;
    }

}
